package middle;

import util.PrintUtils;

public class Solution_59 {

    public int[][] generateMatrix(int n) {
        int[][] rst = new int[n][n];
        int[][] directs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int r = 0, c = -1, dic = 0, count = 0;
        while (true) {
            int rr = r + directs[dic][0];
            int cc = c + directs[dic][1];
            if (rr < 0 || cc < 0 || rr >= n || cc >= n || rst[rr][cc] != 0) {
                dic = (dic + 1) % 4;
                rr = r + directs[dic][0];
                cc = c + directs[dic][1];
            }
            if (rr < 0 || cc < 0 || rr >= n || cc >= n || rst[rr][cc] != 0) {
                break;
            }
            rst[rr][cc] = ++count;
            r = rr;
            c = cc;
        }
        return rst;
    }

    public static void main(String[] args) {
        Solution_59 model = new Solution_59();
        int[][] ints = model.generateMatrix(5);
        for (int[] anInt : ints) {
            PrintUtils.arrayInt(anInt);
        }
    }
}
